package com.ohuang.wallpapermanager.storage.storage

import com.google.gson.reflect.TypeToken
import java.lang.reflect.Type

class GsonSpStorage<T : Any>(var type: Type, var iStorage: SpStorage<String>, var defaultObject:T) : IStorage<T> {
    override fun getValue(): T {
        var value = iStorage.getValue()
        value = value.ifEmpty { GsonUtil.toJson(defaultObject) }
        return GsonUtil.fromJson(value, type) as T
    }

    override fun setValue(value: T) {
        iStorage.setValue(GsonUtil.toJson(value))
    }
}

inline fun <reified T : Any> SpStorageUtil.getForGson(key: String, default: T): IStorage<T> {
    val type = object : TypeToken<T>() {}.type
    return GsonSpStorage(type = type, iStorage = get<String>(key, ""), defaultObject = default)
}
